package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.originskyseed.platform.common.utils.CsvUtil;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.log.model.LoginLog;
import com.originskyseed.platform.user.model.Player;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserCumulativeCharge;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IUserCumulativeChargeService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.UserCumulativeChargeRequestVO;

/**
 * 累充明细表Controller类（OSI_USER_CUMULATIVE_CHARGE）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/userCumulativeCharge")
@BaseLocaleResource(localeFileName = "i18n_user")
public class UserCumulativeChargeController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserCumulativeChargeController.class);

	@DubboReference
	private IUserCumulativeChargeService userCumulativeChargeService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userCumulativeChargeList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<UserCumulativeCharge>> userCumulativeChargeList(HttpServletRequest request) {
		BaseResponseBody<BasePage<UserCumulativeCharge>> result = null;
		try {
			// 请求对象
			UserCumulativeChargeRequestVO requestVO = this.getParameterBean(UserCumulativeChargeRequestVO.class);
			// 用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(userInfo.getSourceSys()!=0) //开放类 查询所有信息
			{
				// 根据范围查询
				List<String> accountList = new ArrayList<>();
				if (userInfo.getType() == 6 || userInfo.getType() == 11) {
					accountList.add(userInfo.getAccount());
				} else {
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					List<String> deptList = new ArrayList<>();
					if (dept != null) {
						selectSonId(dept.getCode(), deptList);
						accountList = this.userInfoService.selectAccountByDeptIds(deptList);
					}
					accountList.add(userInfo.getAccount());
				}
				if (accountList.size() == 0) {
					return new BaseResponseBody<BasePage<UserCumulativeCharge>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), new BasePage(requestVO.getPageNo(), requestVO.getPageSize()));
				}
				requestVO.setAccountList(accountList);
			}
			// 分页查询
			BasePage<UserCumulativeCharge> page = new BasePage<UserCumulativeCharge>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.userCumulativeChargeService.selectListRelUserByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<UserCumulativeCharge>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<UserCumulativeCharge>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 导出信息Excel
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/export.json")
	public void logExport(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			UserCumulativeChargeRequestVO requestVO = this.getParameterBean(UserCumulativeChargeRequestVO.class);
			// 用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(userInfo.getSourceSys()!=0) //开放类 查询所有信息
			{
				// 根据范围查询
				List<String> accountList = new ArrayList<>();
				if (userInfo.getType() == 6 || userInfo.getType() == 11) {
					accountList.add(userInfo.getAccount());
				} else {
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					List<String> deptList = new ArrayList<>();
					if (dept != null) {
						selectSonId(dept.getCode(), deptList);
						accountList = this.userInfoService.selectAccountByDeptIds(deptList);
					}
					accountList.add(userInfo.getAccount());
				}
				if (accountList.size() == 0) {
					return;
				}
				requestVO.setAccountList(accountList);
			}

			List<UserCumulativeCharge> list = this.userCumulativeChargeService.selectListRelUserByMap(requestVO.toMap());
			Map<String, String> header = new LinkedHashMap<>();
			header.put("id", "ID");
			header.put("name", "业务员名称");
			header.put("account", "业务员账号");
			header.put("channelSubId", "子渠道id");
			header.put("type", "累充类型");
			header.put("completionTime", "达成时间");
			header.put("createTime", "添加时间");
			CsvUtil.export(request, response, "累充明细信息", header, list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}


	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		OutputStream os = null;
		try {
			HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
			// 将文件存到指定位置
			this.setResponseHeader(response, fileName);
			os = response.getOutputStream();
			wb.write(os);
			os.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}

	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 查询组织下的部门
	 *
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}